<template>
  <div class="department-container">
    <!-- 顶部搜索区域 -->
    <div class="search-area">
      <div class="search-fields">
        <div class="search-item">
          <label>部门名称</label>
          <el-input
            v-model="searchForm.departmentName"
            placeholder="请输入部门名称"
            style="width: 200px"
            clearable
          />
        </div>
        <div class="search-item">
          <label>状态</label>
          <el-select
            v-model="searchForm.status"
            placeholder="请选择"
            style="width: 120px"
            clearable
          >
            <el-option label="正常" value="正常" />
            <el-option label="停用" value="停用" />
          </el-select>
        </div>
      </div>
      <div class="button-row">
        <div class="search-buttons">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">清空</el-button>
        </div>
        <el-button type="primary" @click="showAddDialog">新增部门</el-button>
      </div>
    </div>

    <!-- 部门列表 -->
    <div class="table-container">
      <div class="table-wrapper">
        <el-table :data="departmentList" style="width: 100%">
        <el-table-column prop="id" label="序号" width="80" align="center" />
        <el-table-column prop="departmentName" label="部门名称" width="180" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <span
              :class="
                scope.row.status === '正常'
                  ? 'status-normal'
                  : 'status-disabled'
              "
            >
              {{ scope.row.status }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="lastUpdateTime"
          label="最后修改时间"
          width="200"
        />
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="showEditDialog(scope.row)">修改</el-button>
            <el-button
              type="text"
              class="delete-button"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="pagination-info">
        共 {{ pagination.total }} 条记录 第 {{ pagination.currentPage }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
      </div>
      <div class="pagination-controls">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :pager-count="9"
        />
        <div class="page-size-selector">
          {{ pagination.pageSize }}条/页
        </div>
        <div class="page-jump">
          跳至
          <el-input-number
            v-model="jumpPage"
            :min="1"
            :max="Math.ceil(pagination.total / pagination.pageSize)"
            @change="handlePageJump"
            style="width: 80px; margin: 0 10px"
          />
          页
        </div>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增部门' : '编辑部门'"
      width="500px"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="departmentName">
          <el-input
            v-model="formData.departmentName"
            placeholder="请输入部门名称"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio value="正常">正常</el-radio>
            <el-radio value="停用">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

// API请求路径 - 稍后替换为实际路径
const API_BASE_URL = "/api";
const API_ENDPOINTS = {
  GET_DEPARTMENTS: `${API_BASE_URL}/departments`,
  ADD_DEPARTMENT: `${API_BASE_URL}/departments`,
  UPDATE_DEPARTMENT: `${API_BASE_URL}/departments`,
  DELETE_DEPARTMENT: `${API_BASE_URL}/departments`,
};

// 搜索表单
const searchForm = reactive({
  departmentName: "",
  status: "",
});

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 20,
});

// 跳转到指定页码
const jumpPage = ref(1);

// 部门列表数据
const departmentList = ref([]);

// 对话框状态
const dialogVisible = ref(false);
const dialogType = ref("add");
const formRef = ref(null);

// 表单数据
const formData = reactive({
  departmentName: "",
  status: "正常",
  id: "",
});

// 表单验证规则
const rules = {
  departmentName: [
    { required: true, message: "请输入部门名称", trigger: "blur" },
  ],
};

// 显示新增对话框
const showAddDialog = () => {
  dialogType.value = "add";
  resetForm();
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (row) => {
  dialogType.value = "edit";
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  formData.departmentName = "";
  formData.status = "正常";
  formData.id = "";
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 获取部门列表 - 完整实现见下方

// 提交表单
const handleSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          // 添加部门
          const response = await axios.post(
            API_ENDPOINTS.ADD_DEPARTMENT,
            formData
          );
          ElMessage.success("添加成功");
          fetchDepartments(); // 重新获取列表
        } else {
          // 编辑部门
          const response = await axios.put(
            `${API_ENDPOINTS.UPDATE_DEPARTMENT}/${formData.id}`,
            formData
          );
          ElMessage.success("编辑成功");
          fetchDepartments(); // 重新获取列表
        }
        dialogVisible.value = false;
      } catch (error) {
        ElMessage.error(dialogType.value === "add" ? "添加失败" : "编辑失败");
        console.error(
          dialogType.value === "add" ? "添加部门失败:" : "编辑部门失败:",
          error
        );
      }
    }
  });
};

// 删除部门
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除部门「${row.departmentName}」吗？`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        // 调用删除API
        await axios.delete(`${API_ENDPOINTS.DELETE_DEPARTMENT}/${row.id}`);
        ElMessage.success("删除成功");
        fetchDepartments(); // 重新获取列表
      } catch (error) {
        ElMessage.error("删除失败");
        console.error("删除部门失败:", error);
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1; // 搜索时重置到第一页
  fetchDepartments();
};

// 重置搜索
const resetSearch = () => {
  searchForm.departmentName = "";
  searchForm.status = "";
  fetchDepartments();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchDepartments();
};

// 页码变化
const handleCurrentChange = (current) => {
  pagination.currentPage = current;
  jumpPage.value = current;
  fetchDepartments();
};

// 页码跳转
const handlePageJump = () => {
  const page = jumpPage.value;
  if (page >= 1 && page <= Math.ceil(pagination.total / pagination.pageSize)) {
    pagination.currentPage = page;
    fetchDepartments();
  }
};

// 设置模拟数据
const setMockData = () => {
  const departments = [
    {
      id: 1,
      departmentName: "咨询部",
      status: "正常",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 2,
      departmentName: "营销部",
      status: "正常",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 3,
      departmentName: "并购投资部",
      status: "停用",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 4,
      departmentName: "技术中心",
      status: "正常",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 5,
      departmentName: "人事部",
      status: "正常",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 6,
      departmentName: "行政部",
      status: "停用",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 7,
      departmentName: "财务部",
      status: "正常",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 8,
      departmentName: "稽核部",
      status: "正常",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 9,
      departmentName: "信息中心",
      status: "停用",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
    {
      id: 10,
      departmentName: "后勤部",
      status: "正常",
      lastUpdateTime: "2025-01-21 08:50:08",
    },
  ];

  // 根据搜索条件过滤
  let filtered = departments;
  if (searchForm.departmentName) {
    filtered = filtered.filter((dept) =>
      dept.departmentName.includes(searchForm.departmentName)
    );
  }
  if (searchForm.status) {
    filtered = filtered.filter((dept) => dept.status === searchForm.status);
  }

  departmentList.value = filtered;
  pagination.total = 20;
};

// 获取部门列表
const fetchDepartments = async () => {
  loading.value = true;
  try {
    const params = {
      departmentName: searchForm.departmentName || '',
      status: searchForm.status || '',
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    };
    const response = await axios.get('/api/departments', { params });
    if (response.data && response.data.list) {
      departmentList.value = response.data.list;
      pagination.total = response.data.total || 0;
    }
  } catch (error) {
    console.error('获取部门列表失败:', error);
    // 使用模拟数据
    departmentList.value = generateMockData();
    pagination.total = 100;
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
    fetchDepartments();
  });
</script>

<style scoped>
.department-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.search-fields {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.button-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.table-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.table-wrapper {
  width: 100%;
  max-width: 100%;
}

.el-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.el-table__header th {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #303133;
}

.status-normal {
  color: #67c23a;
  font-weight: 500;
}

.status-disabled {
  color: #909399;
}

.delete-button {
  color: #f56c6c;
}

.delete-button:hover {
  color: #ff8080;
}

.pagination-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-top: 10px;
}

.page-size-selector {
  color: #606266;
  font-size: 14px;
}

.page-jump {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

/* 调整分页按钮样式 */
.el-pagination__item {
  margin: 0 2px;
  border-radius: 4px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.el-pagination__item.is-active {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

.el-pagination__prev, 
.el-pagination__next {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  border-radius: 4px;
}

/* 按钮样式优化 */
.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>
